<template>
    <div class="chat-wrapper">
        <div class="chat-massage-wrapper">
            <span>{{ targetUserInfo.nickname }}</span>
            <ul class="chat-container" ref="messageListRef">
            <li v-for="(msg, index) in messages" :key="index"
                :class="{ 'my-message': msg.myMessage, 'their-message': !msg.myMessage }">
                <div v-if="!msg.myMessage">
                    <img src="https://pic2.zhimg.com/v2-45e3ca228438d1e4c3e98e38c8f8e4a4_r.jpg?source=1940ef5c"
                        alt="User Avatar" class="avatar" />
                </div>
                <div>
                    <div :class="{ 'username': msg.myMessage }" style="padding: 4px;">{{ msg.nickName }}</div>
                    <div class="message-text">{{ msg.content }}</div>
                </div>
                <div v-if="msg.myMessage">
                    <img src="https://pic2.zhimg.com/v2-45e3ca228438d1e4c3e98e38c8f8e4a4_r.jpg?source=1940ef5c"
                        alt="User Avatar" class="avatar" />
                </div>
            </li>
        </ul>
        <div class="message-input">
            <input type="text" class="el-input" placeholder="请输入消息，按Enter或点击发送按钮发送" v-model="newMessage"
                @keyup.enter="sendMessage" />
            <el-button type="primary" class="btn" @click="sendMessage">发送</el-button>
        </div>
        </div>
        
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, reactive } from 'vue';
import {reqUserInfo} from "@/api/user";
import { useRoute } from 'vue-router';

let route =  useRoute();

const props = defineProps({
    userInfo: {
        type: Object,
    },
})
let indexActive=ref(0)
const wsUrl = 'ws://47.106.183.36:8081';
const socket = ref(null);
const messages = ref([]);
const newMessage = ref('');
//用户信息
const userInfo = JSON.parse(window.localStorage.getItem('userInfo'))
const userId = userInfo.id; // 假定用户ID已知
const nickName = userInfo.nickname;
let targetUserInfo=reactive({})
console.log(userInfo,props.userInfo)
const messageListRef = ref(null);

onMounted(() => {
    getUserList()
    socket.value = new WebSocket(wsUrl);
    socket.value.addEventListener('open', () => {
        console.log('WebSocket connected');
        connectClient()
    });
    socket.value.addEventListener('message', async (event) => {
        try {
            const messageData = JSON.parse(event.data);
            console.log(messageData)
            if (messageData.code == 200 && messageData.data) {
                if(Array.isArray(messageData.data)){
                    messageData.data.forEach(item=>{
                        item.myMessage = false;
                        messages.value.push(item);
                    })
                }else{
                    messageData.data.myMessage = false;
                    messages.value.push(messageData.data);
                    if(messageData.data.userId==targetUserInfo.id){
                        messageData.data.myMessage = false;
                        messages.value.push(messageData.data);
                    }else{
                        
                    }
                    
                }
                
            }
            // 确保DOM更新后再滚动到底部
            await nextTick();
            scrollToBottom();
        } catch (error) {
            console.error('Error parsing received message:', error);
        }
    });
    socket.value.addEventListener('error', (error) => {
        console.error('WebSocket error:', error);
    });

    socket.value.addEventListener('close', () => {
        console.log('WebSocket disconnected');
        socket.value.close();
    });
});

onUnmounted(() => {
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
        socket.value.close();
    }
});
const sendMessage = () => {
    if (newMessage.value.trim() && socket.value.readyState === WebSocket.OPEN) {
        let SendMsg = {
            type: 1,
            userId: userId,
            nickName: nickName,
            targetId:route.query.userId,
            content: newMessage.value,
            time: null
        }
        let myMessage = {
            myMessage: true,
            userId: userId,
            nickName: nickName,
            content: newMessage.value,
            time: new Date().toLocaleString()
        };
        //发送信息
        console.log(SendMsg)
        socket.value.send(JSON.stringify(SendMsg));
        messages.value.push(myMessage);
        newMessage.value = '';
    }
};

const scrollToBottom = () => {
    const messageList = messageListRef.value;
    if (messageList) {
        messageList.scrollTop = messageList.scrollHeight;
    }
};
const userList=reactive([]);
const getUserList = () => {
    reqUserInfo().then(res=>{
        if(res.code==200){
            userList.push(...res.data)
        }
    })
}

const handleClick=(item,index)=>{
    indexActive.value=index
    targetUserInfo=item
    messages.value=[]
    getOffLineMsg(item.id)
    console.log(targetUserInfo)
}
const connectClient=()=>{
    const connectMsg = {
        type: 1001,
        userId: userId,
        nickName: nickName,
        targetId: null,
        content: null,
        time: null
    };
    console.log(connectMsg) 
        //建立连接
    socket.value.send(JSON.stringify(connectMsg));
}
const getOffLineMsg=(targetId)=>{
    const OffLineMsg = {
        type: 3,
        userId: userId,
        nickName: nickName,
        targetId: targetId,
        content: null,
        time: null
    };
        //建立连接
    socket.value.send(JSON.stringify(OffLineMsg));
}
</script>
<style scoped>
.chat-container {
    overflow: auto;
    height: 400px;
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 10px;
    background-color: #F0F2F5;
}

.chat-wrapper {
    width: 100%;
    display: flex;
    
}

.my-message {

    display: flex;
    align-self: flex-end;
    /* 我方消息靠右 */
    /* background-color: lightblue; */
    padding: 10px;

    border-radius: 10px;
}

.their-message {

    display: flex;
    align-self: flex-start;
    /* 对方消息靠左 */
    /* background-color: lightgray; */

    padding: 10px;
    border-radius: 10px;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 20px;
}

.message-input {
    width: 100%;
    display: flex;
    margin-bottom: 50px;
    border-top: 1px solid #ccc;
    padding-top: 20px;
}

.message-text {
    /* width: 100%;
     */
    max-width: 500px;
    background-color: #fff;
    padding: 10px;
    border-radius: 10px;
}

.username {
    /* align-self: flex-end; */
    text-align: end;
}

.el-input {
    width: 100%;
    outline: none;
    border: none;
    background-color: #F0F2F5;
}

.btn {
    background-color: #09C199;
    width: 100px;
}
.user-item{
    border-radius: 4px;
    display: flex;
    padding: 5px;
}

.chat-userList-wrapper{
 
     padding: 7px;   
     flex: 3;
}
.chat-massage-wrapper{
    flex: 6;
}
.nickname{
    margin-left: 10px;
    line-height: 40px;
}
.active{
    background-color: #09C199;
}
</style>